package com.pai4j.ugc.messaegqueue.consumer.redis;
import com.pai4j.common.enums.MessageTypeEnum;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.request.mess.MessageBaseVO;
import com.pai4j.domain.vo.request.mess.MessageNotifyVO;
import com.pai4j.ugc.messaegqueue.service.AbstractPersistentMessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 互动消息持久化队列消费者
 *
 */
@Component
@Lazy(value = false)
@Slf4j
public class PersistentInteractionMessageRedisMQConsumer extends AbstractRedisQueueConsumer<MessageBaseVO> {

   @Resource
   private AbstractPersistentMessageService persistentMessageService;


    public void initBean() {

        new Thread(() -> PersistentInteractionMessageRedisMQConsumer.this.schedule()).start();
    }

    @Override
    protected MessageBaseVO convert(String s) {
        try {
            // 直接反序列化为 MessageNotifyVO，保留互动消息的扩展字段
            return JsonUtil.fromJson(s, MessageNotifyVO.class);
        } catch (Exception ex) {
            log.warn("反序列化为MessageNotifyVO失败，将回退为MessageBaseVO。error={}", ex.getMessage());
            return JsonUtil.fromJson(s, MessageBaseVO.class);
        }
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {

        return MessageQueueEnum.QUEUE_PERSISTENT_INTERACTION_MESSAGE;
    }

    @Override
    protected void receive(MessageBaseVO data) {
        if (data == null) {
            return;
        }
        data.setType(MessageTypeEnum.INTERACTION.getType());
        boolean result = persistentMessageService.persistent(data);
        // 抛出异常，重新入队
        Assert.isTrue(result, "消息持久化失败");
    }

    @Override
    protected void error(MessageBaseVO data, Exception ex) {

    }
}
